package org.aeon.server.handler.Inbound;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.aeon.annotation.Incomplete;
import org.aeon.entity.ChatMessage;
import org.aeon.entity.dto.ChatGroupDto;
import org.aeon.entity.dto.UserDto;
import org.aeon.message.request.GroupChatRequestMessage;
import org.aeon.message.response.GroupChatResponseMessage;
import org.aeon.service.ChatGroupService;
import org.aeon.service.Session;
import org.aeon.service.UserGroupRelationService;
import org.aeon.service.factory.ChatGroupServiceFactory;
import org.aeon.service.factory.SessionFactory;
import org.aeon.service.factory.UserGroupRelationServiceFactory;
import org.aeon.service.factory.UserServiceFactory;

import java.util.Set;

/**
 * @author: MissingAeon
 * @date: 2024/2/19 15:08
 * @description:
 */
@Slf4j
@ChannelHandler.Sharable
@Incomplete
public class GroupChatRequestHandler extends SimpleChannelInboundHandler<GroupChatRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupChatRequestMessage msg) throws Exception {
        final GroupChatResponseMessage resMsg = new GroupChatResponseMessage();

        final ChatGroupDto group = msg.getTo();
        final ChatGroupService groupService = ChatGroupServiceFactory.getService();
        // 判断群聊是否存在
        if (groupService.isChatGroupExist(group.getId())) {
            final UserGroupRelationService groupRelationService = UserGroupRelationServiceFactory.getService();
            final UserDto user = msg.getFrom();
            // 判断查询用户是否为群聊成员
            if (groupRelationService.isGroupMember(group.getId(), user.getId())) {
                // 获取所有成员
                final Set<UserDto> members = groupRelationService.getMembers(group.getId());
                final Session session = SessionFactory.getSession();
                // 创建信息
                resMsg.setMessage(new ChatMessage(msg.getContent(), msg.getCreationTime().getTime(), msg.getFrom().getId(), -group.getId()));
                resMsg.setResponse(true, "发送成功");
                // 一一发送
                members.forEach(member -> {
                    final Channel channel = session.getChannel(member.getId());
                    // 判断在线
                    if (channel != null) {
                        channel.writeAndFlush(resMsg);
                    } else {
                        // 没有在线
                        resMsg.setResponse(true, "离线消息");
                        UserServiceFactory.getService().addMessageToQueue(member.getId(), resMsg);
                    }
                });
            } else {
                resMsg.setResponse(false, "不是该群聊成员");
            }
        } else {
            resMsg.setResponse(false, "该群聊不存在");
        }
        resMsg.setResponseID(msg.getUid());
        ctx.writeAndFlush(resMsg);
    }
}
